package cn.web.controller;

import cn.constant.ApiConstant;
import cn.constant.Messages;
import cn.entity.Article;
import cn.entity.Tag;
import cn.entity.User;
import cn.service.ArticleService;
import cn.service.TagService;
import cn.service.UserService;
import cn.util.AuthUtils;
import cn.web.model.ApiResult;
import cn.web.model.VmArticle;
import cn.web.model.VmUser;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author m on 2023/1/28
 * Description:
 */
@Api(tags = "文章业务")
@RestController
@RequestMapping(ApiConstant.ROUTE_ARTICLE_ROOT)
public class ArticleApiController {

    private final ArticleService articleService;
    private final UserService userService;
    private final TagService tagService;

    @Autowired
    public ArticleApiController(ArticleService articleService, UserService userService, TagService tagService) {
        this.articleService = articleService;
        this.userService = userService;
        this.tagService = tagService;
    }

    public ApiResult addOrUpdate(JSONObject json,UUID id){
        String title = json.getString(ApiConstant.KEY_ARTICLE_TITLE);
        String content = json.getString(ApiConstant.KEY_REAL_CONTENT);
        String token = json.getString(ApiConstant.KEY_TOKEN);
        User user = userService.getById(AuthUtils.getUser(token).getId());
        Article article;

        if(user == null){
            return new ApiResult(false,Messages.USER_NOT_EXISTS.toString(),null);
        }
        if (id == null) {
            article = new Article();
            article.setUser(user);
            article.setCreateTime(new Date());
        }else{
            article = articleService.getById(id);
            if(article==null){
                return new ApiResult(false, Messages.WRONG_ID.toString(),null);
            }
        }


        if(StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
            return new ApiResult(false, Messages.INVALID_FORMAT.toString(),null);
        }

        //获取标签 标签有可能为null,需要判断
        List<Object> list = json.getJSONArray("tags");
        List<Tag> tags = new ArrayList<>();
        list.forEach(o -> {
            if(tagService.getTagByName((String) o)!=null){
                tags.add(tagService.getTagByName((String) o));
            }
        });

        article.setContent(content);
        article.setTitle(title);
        article.setOpen(true);
        article.setTags(tags);

        //新增else修改
        if (id == null) {
            System.out.println(article);
            return new ApiResult(true, Messages.SUCCESS.toString(),VmArticle.create(articleService.createArticle(article)));
        }else{
            Article updated = articleService.updateArticle(article,token);
            String is = json.getString("open");
            if("true".equals(is)){
                article.setOpen(true);
            } else if ("false".equals(is)) {
                article.setOpen(false);
            }
            if(updated == null){
                return new ApiResult(false,Messages.WRONG_ID.toString(),null);
            }else{
                return new ApiResult(true, Messages.SUCCESS.toString(),VmArticle.create(updated));
            }
        }
    }

    //分页获取文章
    @ApiOperation("分页获取文章")
    @GetMapping(ApiConstant.ROUTE_ARTICLE_PAGE)
    public ApiResult get(@RequestParam Integer page,@RequestParam Integer size){
        List<VmArticle> articles = new ArrayList<>();
        articleService.get(page,size)
                .forEach(article -> articles.add(VmArticle.create(article)));
        return new ApiResult(true, Messages.SUCCESS.toString(),articles);
    }

    //新增文章
    @ApiOperation("新增文章")
    @PostMapping(value = ApiConstant.ROUTE_ARTICLE_CREATE,produces = ApiConstant.API_PRODUCES)
    public ApiResult createArticle(@RequestBody JSONObject json){
        return addOrUpdate(json,null);
    }

    //修改文章
    @ApiOperation("修改文章")
    @PutMapping(value = ApiConstant.ROUTE_ARTICLE_UPDATE,produces = ApiConstant.API_PRODUCES)
    public ApiResult updateArticle(@PathVariable UUID id, @RequestBody JSONObject json){
        UUID articleUser = articleService.getById(id).getUser().getId();
        UUID user = AuthUtils.getUser(json.getString(ApiConstant.KEY_TOKEN)).getId();
        //非本人不可更改文章
        if (user == articleUser) {
            return new ApiResult(false,Messages.WRONG_ID.toString(),null);
        }else{
            return addOrUpdate(json,id);
        }

    }

    //删除文章
    @ApiOperation("删除文章")
    @DeleteMapping(value = ApiConstant.ROUTE_ARTICLE_DELETE,produces = ApiConstant.API_PRODUCES)
    public ApiResult deleteArticle(@RequestBody JSONObject json){
        String token = json.getString(ApiConstant.KEY_TOKEN);
        String uuid = json.getString(ApiConstant.KEY_UUID);
        if(StringUtils.isEmpty(token) || StringUtils.isEmpty(uuid)){
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(),null);
        }
        try{
            UUID articleId = UUID.fromString(uuid);
            //仅本人及管理员能删除文章
            Messages msg = articleService.deleteArticle(articleId,token);
            if(!Messages.SUCCESS.equals(msg)){
                return new ApiResult(false,msg.toString(),null);
            }else{
                return new ApiResult(true,msg.toString(),null);
            }
        } catch (Exception e) {
            return new ApiResult(false, Messages.WRONG_ID.toString(),e.getMessage());
        }

    }

    //查找某用户的文章
    @ApiOperation("查找某用户的文章")
    @GetMapping(value = ApiConstant.ROUTE_ARTICLE_GET_ARTICLE)
    public ApiResult getArticles(@PathVariable UUID id){
        User user = userService.getById(id);
        List<VmArticle> articles = new ArrayList<>();
        articleService.getArticlesByUser(user).forEach(article -> articles.add(VmArticle.create(article)));
        return new ApiResult(true, Messages.SUCCESS.toString(),articles);
    }


    //条件查找
    @ApiOperation("条件查找文章")
    @GetMapping(value = ApiConstant.ROUTE_USER_SEARCH)
    public ApiResult searchArticles(@PathVariable("kw") String kw){
        List<VmArticle> vmArticles = new ArrayList<>();
        articleService.search(kw)
                .forEach(article -> vmArticles.add(VmArticle.create(article)));
        return new ApiResult(true, Messages.SUCCESS.toString(),vmArticles);
    }

    //设文章不可见
    @ApiOperation("设文章不可见")
    @PostMapping(value = "/close",produces = ApiConstant.API_PRODUCES)
    public ApiResult closeArticle(@RequestBody JSONObject json){
        String token = json.getString(ApiConstant.KEY_TOKEN);
        UUID articleId = UUID.fromString(json.getString(ApiConstant.KEY_UUID));
        Article article = articleService.getById(articleId);
        VmUser vmUser = AuthUtils.getUser(token);
        //管理员 审核 本人可关闭可见
        if(vmUser.getId()==article.getUser().getId()
            ||vmUser.getType()==User.TYPE_ADMIN
            ||vmUser.getType()==User.TYPE_CERT){
            article.setOpen(false);
            articleService.createArticle(article);
            return new ApiResult(true,Messages.SUCCESS.toString(),VmArticle.create(article));
        }else{
            return new ApiResult(false, Messages.NO_PERMISSION.toString(),null);
        }

    }

}
